package com.hanson.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;

public class Chinese2PinYinUtil {

    /**
    *
    * 汉字转拼音
    *
    * @params: [chinese, combinedInitial]
    * @param: chinese			汉字
    * @param: combinedInitial   组合拼音首字母缩写
    * @return: {@link String}
    * @since: 2022/9/14
    **/
    public static String convert(String chinese, Boolean combinedInitial) {
        if (chinese == null)
            return null;
        StringBuffer pinyin = new StringBuffer();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        
        /**
         * 输出大小写设置
         *
         * LOWERCASE:输出小写
         * UPPERCASE:输出大写
         */
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        /**
         * 输出音标设置
         *
         * WITH_TONE_MARK:直接用音标符（必须设置WITH_U_UNICODE，否则会抛出异常）
         * WITH_TONE_NUMBER：1-4数字表示音标
         * WITHOUT_TONE：没有音标
         */
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        /**
         * 特殊音标ü设置
         *
         * WITH_V：用v表示ü
         * WITH_U_AND_COLON：用"u:"表示ü
         * WITH_U_UNICODE：直接用ü
         */
        defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] arr = chinese.toCharArray();
        int len = arr.length;
        for (char c : arr) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                //汉字
                try {
                    String[] result = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat);
                    if (result != null) {
                        pinyin.append(combinedInitial ? result[0].charAt(0) : result[0]);
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyin.append(c);
            }
        }
        if (StringUtils.isNotBlank(pinyin)){
            return pinyin.toString().toLowerCase();
        }
        return null;
    }
}
